module Tailwindcss
  module Engines
    class << self
      def bundle
        FileUtils.mkdir_p(Rails.root.join("app/assets/builds/tailwind"))
        Rails::Engine.subclasses.select do |engine|
          engine.root.join("app/assets/tailwind/#{engine.engine_name}/engine.css").exist?
        end.each do |engine|
          file_path = Rails.root.join("app/assets/builds/tailwind/#{engine.engine_name}.css")
          FileUtils.rm(file_path) if File.exist?(file_path)
          template = <<~TEMPLATE
            /* DO NOT MODIFY THIS FILE, it was auto-generated by tailwindcss-rails */

            @import "#{engine.root.join("app/assets/tailwind/#{engine.engine_name}/engine.css")}";
          TEMPLATE
          File.open(file_path, 'w') do |file|
            file.puts template
          end
        end
      end
    end
  end
end
